package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author gengjian
 * @date 2024/12/14 00:26:42
 * 自定义拦截器校验是否登录
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //根据请求头中token的key获取token
        String token = request.getHeader("access_token");
        //判断token是否存在
        if (ObjectUtils.isEmpty(token)){
            //不存在则未登录
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        //解析token 方法内部会判断token是否合法
        Claims claims = JwtUtil.parseToken(token);
        //通过解析后拿到登录用户信息
        //integer 包装类不能自动提升为Long包装类
        Long userId = Long.valueOf(claims.get("userId").toString());
        String userName = (String) claims.get("userName");
        //将用户信息存到本地线程
        LoginUserContext.setLoginUser(new LoginUser(userId,userName));
        //都ok返回true 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //拦截器完成后清空本地线程
        LoginUserContext.clear();
    }
}
